package com.leosoft.heatmonitor.service.transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.leosoft.heatmonitor.dao.DeviceDAO;
import com.leosoft.heatmonitor.dao.ProjectDAO;
import com.leosoft.heatmonitor.dao.TargetDAO;
import com.leosoft.heatmonitor.dao.UserDAO;
import com.leosoft.heatmonitor.model.Project;
import com.leosoft.heatmonitor.model.Target;
import com.leosoft.heatmonitor.model.User;

@Component("deviceService")
public class DeviceService {
	@Autowired
	private DeviceDAO deviceDAO;
	@Autowired
	private ProjectDAO projectDAO;
	@Autowired
	private TargetDAO targetDAO;
	@Autowired
	private UserDAO userDAO;

	public Map<String, Object> list(int startIndex, int length, List<String[]> wherePart, List<String[]> odrerPart,
			String username) {
		User user = userDAO.getUserByName(username);
		if (!user.getRoles().isEmpty()) {
			if (user.getRoles().get(0).getRole().equals("PM")) {
				return deviceDAO.list(startIndex, length, wherePart, odrerPart, user.getId());
			} else {
				return deviceDAO.list(startIndex, length, wherePart, odrerPart, "");
			}
		}

		return null;
	}

	public boolean create(String projectId, String name, String key, String type, String format, String[] targetIds) {
		if (deviceDAO.notExist(projectId, key)) {
			Project project = projectDAO.getProjectById(projectId);
			List<Target> targets = new ArrayList<>();
			for (String targetId : targetIds) {
				Target target = targetDAO.getTargetById(targetId);
				targets.add(target);
			}
			deviceDAO.create(project, name, key, type, format, targets);
			return true;
		}
		return false;
	}

	public void delete(String id) {
		deviceDAO.delete(id);
	}

	public void update(String id, String projectId, String name, String key, String type, String format,
			String[] targetIds) {
		Project project = projectDAO.getProjectById(projectId);
		List<Target> targets = new ArrayList<>();
		for (String targetId : targetIds) {
			Target target = targetDAO.getTargetById(targetId);
			targets.add(target);
		}
		deviceDAO.update(id, project, name, key, type, format, targets);
	}

	public List<String> loadDevice(String projectId) {
		return deviceDAO.loadDevice(projectId);
	}

}
